/**
 * 项目名：五位一体化工安全信息平台
 * 日期：    2019-12-09 17:24:07
 * Copyright (c) 2015- joysuch-版权所有
 */

package com.joysuch.wwyt.bp.service.impl;

import com.google.gson.Gson;
import com.joysuch.wwyt.bp.bean.BpExamAssessDetailBean;
import com.joysuch.wwyt.bp.bean.BpExamAssessEditBean;
import com.joysuch.wwyt.bp.bean.BpExamAssessListBean;
import com.joysuch.wwyt.bp.bean.BpExamAssessListBean.Search;
import com.joysuch.wwyt.bp.entity.BpDepart;
import com.joysuch.wwyt.bp.entity.BpExamAssess;
import com.joysuch.wwyt.bp.entity.BpExamStandard;
import com.joysuch.wwyt.bp.entity.dsl.QBpExamAssess;
import com.joysuch.wwyt.bp.repository.BpDepartDao;
import com.joysuch.wwyt.bp.repository.BpExamAssessDao;
import com.joysuch.wwyt.bp.repository.BpExamStandardDao;
import com.joysuch.wwyt.bp.service.BpExamAssessService;
import com.joysuch.wwyt.core.common.util.PageDataUtils;
import com.joysuch.wwyt.core.common.util.PageDataUtils.PageDataConvert;
import com.joysuch.wwyt.core.entity.dsl.QBaseUser;
import com.joysuch.wwyt.core.exception.BusinessRestrictionsException;
import com.joysuch.wwyt.core.repository.BaseUserDao;
import com.joysuch.wwyt.core.service.BizCodeGeneratorFacade;
import com.joysuch.wwyt.util.FloatUtil;
import com.querydsl.core.types.ExpressionUtils;
import com.querydsl.core.types.Predicate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
@Transactional
public class BpExamAssessServiceImpl implements BpExamAssessService {

    @Autowired
    private BpExamAssessDao dao;
    @Autowired
    private BizCodeGeneratorFacade bizCodeGeneratorFacade;

    @Autowired
    private BpExamStandardDao bpExamStandardDao;

    @Autowired
    private BaseUserDao baseUserDao;
    @Autowired
    private BpDepartDao bpDepartDao;

    @Override
    public BpExamAssess add(BpExamAssessEditBean entity) throws Exception {
        BpExamAssess content = new BpExamAssess();
        // 考核标准ID
        content.setExamId(entity.getExamId());
        // 考核编号
        content.setNum(bizCodeGeneratorFacade.kaohe());
        // 考核人员ID
        content.setExamPersonId(entity.getExamPersonId());
        // 考核时间
        content.setExamTime(entity.getExamTime());
        // 考官ID
        content.setExaminerId(entity.getExaminerId());
        // 考核项目集合
        content.setItemExam(entity.getItemExam());
        content.setState(entity.getState());

        Gson gson = new Gson();
        List<Map<String, Object>> itemExamList = gson.fromJson(entity.getItemExam(), ArrayList.class);
        float totalScore = 0f;
        for (Map<String, Object> tempMap : itemExamList) {
            try {
                float tempScore = Float.parseFloat(tempMap.get("itemScore").toString());
                if (!FloatUtil.judgeFloat(tempScore)) {
                    throw new IllegalArgumentException("");
                }
                totalScore += tempScore;
            } catch (Exception e) {
                throw new IllegalArgumentException("分值输入有误", e);
            }
        }
        // 考核结果
        content.setItemExamScore(totalScore);
//        BpExamStandard bpExamStandard = bpExamStandardDao.findById(entity.getExamId()).get();
//        content.setDepartId(bpExamStandard.getDepartId());
        content.setDepartId(entity.getDepartId());
        return dao.save(content);
    }

    @Override
    public void update(BpExamAssessEditBean entity) throws Exception {
        BpExamAssess content = dao.findById(entity.getId()).get();
        // ID，主键
        // 考核标准ID
        content.setExamId(entity.getExamId());
        // 考核人员ID
        content.setExamPersonId(entity.getExamPersonId());
        // 考核时间
        content.setExamTime(entity.getExamTime());
        // 考官ID
        content.setExaminerId(entity.getExaminerId());
        // 考核项目集合
        content.setItemExam(entity.getItemExam());
        Gson gson = new Gson();
        List<Map<String, Object>> itemExamList = gson.fromJson(entity.getItemExam(), ArrayList.class);
        float totalScore = 0;
        for (Map<String, Object> tempMap : itemExamList) {
            try {
                float tempScore = Float.parseFloat(tempMap.get("itemScore").toString());
                if (!FloatUtil.judgeFloat(tempScore)) {
                    throw new IllegalArgumentException("");
                }
                totalScore += tempScore;
            } catch (Exception e) {
                throw new IllegalArgumentException("分值输入有误", e);
            }
        }
        // 考核结果
        content.setItemExamScore(totalScore);
        content.setState(entity.getState());
//        BpExamStandard bpExamStandard = bpExamStandardDao.findById(entity.getExamId()).get();
//        content.setDepartId(bpExamStandard.getDepartId());
        content.setDepartId(entity.getDepartId());
        dao.save(content);
    }

    @Override
    public Page<BpExamAssessListBean> findByPage(Pageable page, Search condition) {
        Predicate predicate = prepareListSearchCondition(condition);
        page = PageDataUtils.addOrderByDesc(page, "id");
        Page<BpExamAssess> data = predicate == null ? dao.findAll(page) : dao.findAll(predicate, page);
        return PageDataUtils.convertPageData(data, new PageDataConvert<BpExamAssessListBean, BpExamAssess>() {

            @Override
            public BpExamAssessListBean convert(BpExamAssess f) {
                BpExamAssessListBean bean = new BpExamAssessListBean();

                // ID，主键
                bean.setId(f.getId());

                // 考核标准ID
                bean.setExamId(f.getExamId());
                if (f.getExamId() != null) {
                    bpExamStandardDao.findById(f.getExamId()).ifPresent(e -> bean.setExamName(e.getExamName()));
                }

                // 考核编号
                bean.setNum(f.getNum());

                // 考核人员ID
                bean.setExamPersonId(f.getExamPersonId());
                if (f.getExamPersonId() != null) {
                    bean.setExamPerson(baseUserDao.findById(f.getExamPersonId()).get().getRealName());
                }

                // 考核时间
                bean.setExamTime(f.getExamTime());

                // 考官ID
                bean.setExaminerId(f.getExaminerId());
                if (f.getExaminerId() != null) {
                    bean.setExaminer(baseUserDao.findById(f.getExaminerId()).get().getRealName());
                }

                // 考核项目集合
                bean.setItemExam(f.getItemExam());

                // 考核结果
                bean.setItemExamScore(f.getItemExamScore());
                if (f.getState() != null && f.getState() == 0) {
                    bean.setExamResult("通过");
                } else {
                    bean.setExamResult("未通过");
                }
                // if (f.getItemExamScore() == null) {
                // bean.setExamResult("没有分数");
                // } else if (f.getItemExamScore() >= 60) {
                // bean.setExamResult(String.format("通过(%d分)", f.getItemExamScore()));
                // } else {
                // bean.setExamResult(String.format("未通过(%d分)", f.getItemExamScore()));
                // }
                // if(bean.gets)
                // 责任部门
                if (f.getDepartId() != null) {
                    BpDepart bpDepart = bpDepartDao.findById(f.getDepartId()).get();
                    bean.setDepartName(bpDepart.getName());
                }
                return bean;
            }

        });
    }

    private Predicate prepareListSearchCondition(Search condition) {
        QBpExamAssess qBpExamAssess = QBpExamAssess.bpExamAssess;
        Predicate predicate = null;
        if (condition.getExamPerson() != null && !"".equals(condition.getExamPerson())) {
            QBaseUser qBaseUser = QBaseUser.baseUser;
            Predicate pre = qBaseUser.realName.like("%" + condition.getExamPerson() + "%");
            List<Long> userIds = new ArrayList<>();
            baseUserDao.findAll(pre).forEach(t -> {
                userIds.add(t.getId());
            });
            predicate = qBpExamAssess.examPersonId.in(userIds);
        }
        if (condition.getExamResult() != null) {
            if (condition.getExamResult() == 1) {
                // 通过
                predicate = ExpressionUtils.and(predicate, qBpExamAssess.state.eq(0));
            } else {
                // 未通过
                predicate = ExpressionUtils.and(predicate,
                        ExpressionUtils.or(qBpExamAssess.state.ne(0), qBpExamAssess.state.isNull()));
            }
        }
        if (condition.getDepartId() != null) {
            predicate = qBpExamAssess.departId.eq(condition.getDepartId());
        }
        return predicate;
    }

    @Override
    public void delete(Long id) throws BusinessRestrictionsException {
        // 校验业务逻辑是否允许删除。如本数据被其他业务关联，删除后导致其他业务不可用。不能删除时将抛出业务异常
        checkBussinessRestrictions(id);
        dao.deleteById(id);
    }

    /**
     * 校验业务逻辑是否允许删除。如本数据被其他业务关联，删除后导致其他业务不可用
     *
     * @param id 要删除的业务ID
     * @throws BusinessRestrictionsException 抛出的业务异常
     */
    private void checkBussinessRestrictions(Long id) throws BusinessRestrictionsException {

    }

    @Override
    public BpExamAssess findById(Long id) {
        BpExamAssess bpExamAssess = dao.findById(id).get();
        if (bpExamAssess!=null && bpExamAssess.getDepartId()!=null){
            BpDepart bpDepart = bpDepartDao.findById(bpExamAssess.getDepartId()).get();
            bpExamAssess.setDepartName(bpDepart.getName());
        }
        return bpExamAssess;
    }

    @Override
    public BpExamAssessDetailBean getById(Long id) {
        BpExamAssess entity = findById(id);
        BpExamAssessDetailBean bean = new BpExamAssessDetailBean();
        // ID，主键
        bean.setId(entity.getId());

        // 考核标准ID
        bean.setExamId(entity.getExamId());
        if (entity.getExamId() != null) {
            bpExamStandardDao.findById(entity.getExamId()).ifPresent(e -> bean.setExamName(e.getExamName()));
        }

        // 考核编号
        bean.setNum(entity.getNum());

        // 考核人员ID
        bean.setExamPersonId(entity.getExamPersonId());
        bean.setExamPerson(baseUserDao.getBaseUserNameById(entity.getExamPersonId()));

        // 考核时间
        bean.setExamTime(entity.getExamTime());

        // 考官ID
        bean.setExaminerId(entity.getExaminerId());
        bean.setExaminer(baseUserDao.getBaseUserNameById(entity.getExaminerId()));

        // 考核项目集合
        bean.setItemExam(entity.getItemExam());

        // 考核结果
        bean.setItemExamScore(entity.getItemExamScore());
        if (entity.getDepartId() != null) {
            BpDepart bpDepart = bpDepartDao.findById(entity.getDepartId()).get();
            bean.setDepartName(bpDepart.getName());
        }
        bean.setDepartId(entity.getDepartId());
        return bean;
    }

}
